package com.mlan.userap.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.baseokhttp.util.JsonMap;
import com.mlan.userap.R;
import com.mlan.userap.model.CallEvent;
import com.mlan.userap.model.ChatGroupInfo;
import com.mlan.userap.model.MsgEvent;
import com.mlan.userap.untils.Convert;
import com.mlan.userap.untils.GenerateTestUserSig;
import com.mlan.userap.viewmodel.CallViewModel;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class CallActivity extends BaseActivity {

    private TextView tvContactName, text_speaker, text_mute;
    private TextView tvCallStatus;
    private ImageView ivContactAvatar;
    private LinearLayout btnMute, btn_jieting, ll_speaker;
    private LinearLayout btnHangup;
    private LinearLayout ll_user_infor;
    private ImageView btnSpeaker;
    private boolean isMuted = false;
    private boolean isSpeakerOn = false;

    //视频组建
    TXCloudVideoView txcvv_main_local;
    TXCloudVideoView txcvv_main_local2;

    private TRTCCloud trtcCloud;
    //判断语音是主动还是被动 主动是0 被动是1
    CallViewModel callViewModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call);
        initView();
        ImmersionBar.with(this)
                .statusBarColor(R.color.background_light)
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.black)
                .keyboardEnable(true)
                .fitsSystemWindows(true)
                .init();
        callViewModel = new ViewModelProvider(this).get(CallViewModel.class);

        initData();
        initEvent();
    }

    private void initEvent() {
        callViewModel.groupEntity.observe(this, groupEntity -> {
            callViewModel.groupId = groupEntity.getGroupId();
            callViewModel.name = groupEntity.getGroupName();
            //自己的userid
            callViewModel.userid = groupEntity.getUserList().get(1).getUserId();
            //对方的userid
            callViewModel.otherUserid = groupEntity.getUserList().get(0).getUserId();
            callViewModel.callService();
        });
        // 麦克风（静音）按钮
        btnMute.setOnClickListener(v -> {
            isMuted = !isMuted;
//            btnMute.setImageResource(isMuted ? R.drawable.ic_mute_on : R.drawable.ic_mute_off);
            trtcCloud.muteLocalAudio(isMuted);
//            Toast.makeText(CallActivity.this, isMuted ? "已静音" : "已取消静音", Toast.LENGTH_SHORT).show();
            text_mute.setText(isMuted ? "麦克风已关" : "麦克风已开");
        });

        //接听电话
        btn_jieting.setOnClickListener(view -> {
            callViewModel.upCallService();
        });


        // 挂断按钮
        btnHangup.setOnClickListener(v -> {
            callViewModel.hangupService(this::finish);
//
        });

        // 扬声器（免提）按钮
        btnSpeaker.setOnClickListener(v -> {
            isSpeakerOn = !isSpeakerOn;
            btnSpeaker.setImageResource(isSpeakerOn ? R.drawable.ic_speaker_on : R.drawable.ic_speaker_off);
//            Toast.makeText(CallActivity.this, isSpeakerOn ? "扬声器已开" : "扬声器已关", Toast.LENGTH_SHORT).show();
            text_speaker.setText(isSpeakerOn ? "扬声器已开" : "扬声器已关");
            trtcCloud.setAudioRoute(isSpeakerOn ? TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER : TRTCCloudDef.TRTC_AUDIO_ROUTE_EARPIECE);
        });
    }

    private void initData() {
        // 获取传递的群组信息
        callViewModel.callType.setValue(getIntent().getIntExtra("callType", 0));
        callViewModel.stype.setValue(getIntent().getIntExtra("stype", 0));
        if (getIntent().getStringExtra("groupInfo") != null) {
            String groupInfoJson = getIntent().getStringExtra("groupInfo");
            callViewModel.groupEntity.setValue(Convert.fromJson(groupInfoJson, ChatGroupInfo.class));
            btn_jieting.setVisibility(View.GONE);
        }
        if (callViewModel.callType.getValue() == 1) {
            //被动打开电话页面
            if (getIntent().getStringExtra("eventGroupInfo") != null) {
                String groupInfoJson = getIntent().getStringExtra("eventGroupInfo");
                callViewModel.callService(groupInfoJson);
            }
        }

        callViewModel.upCallType.observe(this, callType -> {
            if (callType == 1) {
                btn_jieting.setVisibility(View.GONE);
                btnMute.setVisibility(View.VISIBLE);
                ll_speaker.setVisibility(View.VISIBLE);
                tvCallStatus.setVisibility(View.GONE);
            }
            CallOne();
        });
    }


    private void initView() {
        ll_user_infor = findViewById(R.id.ll_user_infor);
        txcvv_main_local2 = findViewById(R.id.txcvv_main_local2);
        txcvv_main_local = findViewById(R.id.txcvv_main_local);
        ll_speaker = findViewById(R.id.ll_speaker);
        btn_jieting = findViewById(R.id.btn_jieting);
        text_speaker = findViewById(R.id.text_speaker);
        text_mute = findViewById(R.id.text_mute);
        btnSpeaker = findViewById(R.id.btn_speaker);
        tvContactName = findViewById(R.id.tv_contact_name);
        tvCallStatus = findViewById(R.id.tv_call_status);
        ivContactAvatar = findViewById(R.id.iv_contact_avatar);
        btnMute = findViewById(R.id.btn_mute);
        btnHangup = findViewById(R.id.btn_hangup);
    }

    //主动打电话的方法
    private void CallOne() {
        // 设置通话对象信息
        tvContactName.setText(callViewModel.name);
        tvCallStatus.setText("等待对方接受邀请...");
        Log.d("zdl", "====callViewModel.groupAvatar=========" + callViewModel.groupAvatar);
        // 加载群组头像
        Glide.with(this)
                .load(callViewModel.groupAvatar)
                .circleCrop()
                .into(ivContactAvatar);

        TRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();
        trtcParams.sdkAppId = callViewModel.sdkAppId;
        trtcParams.userId = callViewModel.userid + ""; // 自己的userid
        trtcParams.roomId = callViewModel.roomId;
        trtcParams.userSig = callViewModel.userSig;

        Log.d("zdl", "==========callViewModel.roomId=======" + callViewModel.roomId);
        Log.d("zdl", "==========callViewModel.userid=======" + callViewModel.userid);
        Log.d("zdl", "==========callViewModel.sdkAppId=======" + callViewModel.sdkAppId);
        Log.d("zdl", "==========callViewModel.userSig=======" + callViewModel.userSig);
        Log.d("zdl", "==========callViewModel.stype=======" + callViewModel.stype.getValue());

        trtcCloud = TRTCCloud.sharedInstance(getApplicationContext());

        trtcCloud.setListener(new TRTCCloudListener() {
            @Override
            public void onError(int errCode, String errMsg, Bundle extraInfo) {
                super.onError(errCode, errMsg, extraInfo);
                String notificaiton = "Error Code: " + errCode + ", Error Message: " + errMsg + ", extraInfo: " + extraInfo;
                Log.d("zdl", "====onError=====" + notificaiton);
//            Toast.makeText(getApplicationContext(), notificaiton, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onEnterRoom(long result) {
                super.onEnterRoom(result);
                Log.d("zdl", "====onEnterRoom====result=" + result);
                if (result > 0) {
                    Toast.makeText(getApplicationContext(), "进房成功！", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "进房失败！", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onUserVideoAvailable(String userId, boolean available) {
                super.onUserVideoAvailable(userId, available);
                Log.d("zdl", "==========onUserVideoAvailable===============userId=" + userId + ", available=" + available);

                if (available) {
                    // 确保使用回调中提供的userId
                    Log.d("zdl", "准备渲染远程视频，userId=" + userId + ", otherUserId=" + callViewModel.otherUserid);

                    // 设置远端渲染参数
                    TRTCCloudDef.TRTCRenderParams renderParams = new TRTCCloudDef.TRTCRenderParams();
                    renderParams.fillMode = TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;
                    trtcCloud.setRemoteRenderParams(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, renderParams);

                    // 显示渲染视图
                    txcvv_main_local2.setVisibility(View.VISIBLE);

                    // 播放远端画面 - 使用回调中的userId而不是硬编码
                    trtcCloud.startRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, txcvv_main_local2);
                } else {
                    // 视频不可用时停止渲染
                    Log.d("zdl", "停止渲染远程视频，userId=" + userId);
                    trtcCloud.stopRemoteView(userId);
                    txcvv_main_local2.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFirstVideoFrame(String userId, int streamType, int width, int height) {
                super.onFirstVideoFrame(userId, streamType, width, height);
                Log.d("zdl", "==========onFirstVideoFrame===============userId=" + userId);
                // 第一帧视频渲染回调，可以用于显示视频已开始
            }

            @Override
            public void onRemoteUserEnterRoom(String userId) {
                super.onRemoteUserEnterRoom(userId);
                Log.d("zdl", "==========onRemoteUserEnterRoom===============userId=" + userId);
                // 远程用户进房回调，可以用于初始化UI
            }

            @Override
            public void onRemoteUserLeaveRoom(String userId, int reason) {
                super.onRemoteUserLeaveRoom(userId, reason);
                Log.d("zdl", "==========onRemoteUserLeaveRoom===============userId=" + userId);
                // 远程用户离开房间
                trtcCloud.stopRemoteView(userId);
                txcvv_main_local2.setVisibility(View.GONE);
            }
        });

        if (callViewModel.stype.getValue() == 1) {
            txcvv_main_local.setVisibility(View.VISIBLE);
            txcvv_main_local2.setVisibility(View.VISIBLE);
            ll_user_infor.setVisibility(View.GONE);

            // 设置视频通话场景
            trtcCloud.enterRoom(trtcParams, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);

            // 开启麦克风采集
            trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);

            // 设置音频质量
            trtcCloud.setAudioQuality(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);

            // 设置视频编码参数
            TRTCCloudDef.TRTCVideoEncParam encParam = new TRTCCloudDef.TRTCVideoEncParam();
            encParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360;
            encParam.videoFps = 15;
            encParam.videoBitrate = 600;
            encParam.enableAdjustRes = true;
            trtcCloud.setVideoEncoderParam(encParam);

            // 开启本地视频预览
            trtcCloud.startLocalPreview(true, txcvv_main_local);
        } else {
            trtcCloud.enterRoom(trtcParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
            trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);
            trtcCloud.setAudioQuality(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
        }
    }

    private void exitRoom() {
        if (trtcCloud != null) {
            trtcCloud.stopLocalAudio();
            trtcCloud.exitRoom();
        }
    }

    @Override
    protected void onDestroy() {
        exitRoom();
        if (trtcCloud != null) {
            trtcCloud.setListener(null);
            TRTCCloud.destroySharedInstance();
            trtcCloud = null;
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void msgEvent(MsgEvent event) {
        Log.d("zdl", "============" +new Gson().toJson(event.data) );
        JsonMap jsonMap = null;
        if (event.code.equals("PushRoom")){
            jsonMap = new JsonMap(event.data.toString());
        }else {
            jsonMap = new JsonMap(new Gson().toJson(event.data));
        }
        JsonMap enterInfo = jsonMap.getJsonMap("enterInfo");
        if (enterInfo != null) {
            Log.d("zdl", "======callViewModel.roomId==========" + callViewModel.roomId);
            Log.d("zdl", "======enterInfo.roomId==========" + enterInfo.getString("roomId"));
            if (enterInfo.getString("roomId").equals(callViewModel.roomId + "")) {
                //接听
                btn_jieting.setVisibility(View.GONE);
                btnMute.setVisibility(View.VISIBLE);
                ll_speaker.setVisibility(View.VISIBLE);
                tvCallStatus.setVisibility(View.GONE);
                return;
            }
        }
//        {"msgId":"8040f46ec3254771bef365ce00e1eb2d","groupId":"2","uidFrom":"124","msgType":"7","msgContent":"已拒绝","fileInfo":"null","msgTicks":"1747660784149"}
        Log.d("zdl", "===groupId==" + jsonMap.getString("groupId"));
        if (callViewModel.groupId.equals(jsonMap.getString("groupId"))) {
            Log.d("zdl", "===msgContent==" + jsonMap.getString("msgContent"));
            if (event.code.equals("Chat")) {
                Log.d("zdl", "=====");
                finish();
            }
        }
    }
}